package com.handpay.nocardpay.baselibrary.guide.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.account.view.activity.LoginActivity;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseErrorInfo;
import com.handpay.nocardpay.baselibrary.commbase.view.activity.BaseActivity;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.db.ormlite.DataBaseComponentModel;
import com.handpay.nocardpay.baselibrary.download.view.activity.DownloadApkActivity;
import com.handpay.nocardpay.baselibrary.guide.presenter.VersionPresenterImpl;
import com.handpay.nocardpay.baselibrary.guide.view.IVersionView;
import com.handpay.nocardpay.baselibrary.guide.view.fragment.AdvertisingFragment;
import com.handpay.nocardpay.baselibrary.http.HttpClientImpl;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentConfigUtil;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentItemBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentMappingItemBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentRelationItemBean;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WelcomeActivity extends BaseActivity implements IVersionView {
    private boolean isTestUrl = true;
    private AlertDialog dialog;
    private VersionPresenterImpl mVersionPresenter;
    private HashMap<String, Object> paramers;

    @Override
    public void lastVersion() {
        goLogin();
    }

    /**
     * 登录
     */
    private void goLogin() {
        boolean showAdvertising = PreferenceManager.getInstance(this).getBoolean("advertising", false);
        if (showAdvertising) {
            Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
            this.startActivity(intent);
            this.finish();
        } else {
            loadRootFragment(R.id.fl_container, AdvertisingFragment.newInstance());
        }
    }

    @Override
    public void noRemindVersion(String title, String message, final String url, final String version) {
        goLogin();
    }

    @Override
    public void showProgress() {
        DialogUtils.showProgressDialog(this, "", getString(R.string.loading), false);
    }

    @Override
    public void hideProgress() {
        DialogUtils.closeProgressDialog();
    }

    @Override
    public void showErrorAlert(BaseErrorInfo baseErrorInfo) {
        DialogUtils.showAlertDialog(this, getString(R.string.dialog_title), baseErrorInfo.errMessage, false, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                WelcomeActivity.this.finish();
            }
        });
    }

    @Override
    public void forcedUpdateApk(String title, String message, final String url) {
        DialogUtils.showAlertDialog(this, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goToDownloadActivity(WelcomeActivity.this, url);
            }
        });
    }

    @Override
    public void normalUpdateApk(String title, String message, final String url, final String version) {
        DialogUtils.showAlertDialog(this, title, message, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goToDownloadActivity(WelcomeActivity.this, url);
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                lastVersion();
                PreferenceManager.getInstance(WelcomeActivity.this.getApplicationContext()).putBoolean(NoCardPayConstant.IS_NOT_REMIND, false);
            }
        }, getResources().getString(R.string.no_longer_remind), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
                PreferenceManager.getInstance(WelcomeActivity.this.getApplicationContext()).putBoolean(NoCardPayConstant.IS_NOT_REMIND, true);
                PreferenceManager.getInstance(WelcomeActivity.this.getApplicationContext()).putString(NoCardPayConstant.NOT_REMIND_VERSION, version);
                lastVersion();
            }
        });
    }

    protected void goToDownloadActivity(Activity activity, String url) {
        Intent intent = new Intent(activity, DownloadApkActivity.class);
        intent.putExtra(DownloadApkActivity.DOWNLOAD_APK_URL, url);
        activity.startActivity(intent);
    }

    @Override
    public void initData() {
        mVersionPresenter = new VersionPresenterImpl(this, this.getApplicationContext());
        paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.VERSION, ClientEngine.getInstance().VERSION);
        paramers.put(BaseProtocolKey.PLATFORM, ClientEngine.getInstance().MOBILE_TYPE);
        paramers.put(BaseProtocolKey.CHANNEL, NoCardPayConfig.CLIENTCHANNEL);

        DataBaseComponentModel dbModel = new DataBaseComponentModel(this);

        //初始化组件数据库
        if (dbModel.queryComponentMappingList() == null || dbModel.queryComponentMappingList().size() == 0) {
            List<ComponentRelationItemBean> dbComponentRelationList = dbModel.queryComponentRelationList();
            if (dbComponentRelationList == null || dbComponentRelationList.size() == 0) {
                ArrayList<ComponentRelationItemBean> componentRelationList = ComponentConfigUtil.getComponentRelationListFromConfig(this);
                for (ComponentRelationItemBean bean : componentRelationList) {
                    dbModel.addComponentRelation(bean);
                }
            }

            List<ComponentMappingItemBean> dbComponentMappingList = dbModel.queryComponentMappingList();
            if (dbComponentMappingList == null || dbComponentMappingList.size() == 0) {
                ArrayList<ComponentMappingItemBean> componentMappingList = ComponentConfigUtil.getComponentMappingListFromConfig(this);
                for (ComponentMappingItemBean bean : componentMappingList) {
                    dbModel.addComponentMapping(bean);
                }
            }

            List<ComponentItemBean> dbComponentList = dbModel.queryComponentList();
            if (dbComponentList == null || dbComponentList.size() == 0) {
                ArrayList<ComponentItemBean> componentList = ComponentConfigUtil.getComponentListFromConfig(this);
                for (ComponentItemBean bean : componentList) {
                    dbModel.addComponent(bean);
                }
            }
        }

    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_welcome;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
//        StatusBarUtil.setTranslucentForImageView(this,0,null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * init http
         */
        HttpClientImpl.init(getApplicationContext());
        ClientEngine.getInstance().saveGlobal(NoCardPayConstant.VerifyVersionOK, false);
        if (NoCardPayConfig.ENV.CANSET) {
            if (dialog != null && dialog.isShowing()) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater li = LayoutInflater.from(this);
            View content = li.inflate(R.layout.layout_dialog, null);
            final EditText etDomain = (EditText) content.findViewById(R.id.et_domain);
            final EditText etDomains = (EditText) content.findViewById(R.id.et_domains);


            String urls = NoCardPayConfig.ENV.SERVER;
            if (isTestUrl) {
                etDomain.setHint(urls.substring(0, urls.lastIndexOf(".") + 1));
                etDomains.setHint(urls.substring(urls.lastIndexOf(".") + 1));
                etDomains.setVisibility(View.VISIBLE);
            } else {
                etDomains.setVisibility(View.GONE);
                etDomain.setHint(urls);
            }

            final EditText etPort = (EditText) content.findViewById(R.id.et_port);
            etPort.setHint(String.valueOf(NoCardPayConfig.ENV.PORT));
            final EditText etChannel = (EditText) content.findViewById(R.id.et_channel);
            etChannel.setHint(NoCardPayConfig.ENV.CHAN);

            final EditText etClientVersion = (EditText) content.findViewById(R.id.et_clientVersion);
            etClientVersion.setHint(ClientEngine.getInstance().VERSION);

            final EditText etClientChannel = (EditText) content.findViewById(R.id.et_clientchannel);
            etClientChannel.setHint(NoCardPayConfig.CLIENTCHANNEL);

            final EditText qr_code_url_et = (EditText) content.findViewById(R.id.qr_code_url_et);
            final EditText no_card_pay_url_et = (EditText) content.findViewById(R.id.no_card_pay_url_et);
            final EditText lottery_url_et = (EditText) content.findViewById(R.id.lottery_url_et);

            qr_code_url_et.setText(ClientEngine.getInstance().QR_CODE_PAY_URL_TEST);
            no_card_pay_url_et.setText(ClientEngine.getInstance().NO_CARD_PAYMENT_URL_TEST);
            lottery_url_et.setText(ClientEngine.getInstance().LOTTERY_URL_TEST);


            builder.setView(content);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    String domain1 = etDomain.getText().toString();
                    String domain = domain1;
                    if (isTestUrl) {
                        if (TextUtils.isEmpty(domain1)) {
                            domain1 = etDomain.getHint().toString();
                        }
                        String domain2 = etDomains.getText().toString();
                        if (TextUtils.isEmpty(domain2)) {
                            domain2 = etDomains.getHint().toString();
                        }
                        domain = domain1 + domain2;
                    }
                    if (TextUtils.isEmpty(domain)) {
                        domain = NoCardPayConfig.ENV.SERVER;
                    }
                    if (TextUtils.isEmpty(domain)) {
                        domain = etDomain.getHint().toString();
                    }
                    String port = etPort.getText().toString();
                    if (TextUtils.isEmpty(port)) {
                        port = etPort.getHint().toString();
                    }
                    String channel = etChannel.getText().toString();
                    if (TextUtils.isEmpty(channel)) {
                        channel = etChannel.getHint().toString();
                    }
                    String clientVersion = etClientVersion.getText().toString();
                    if (TextUtils.isEmpty(clientVersion)) {
                        clientVersion = etClientVersion.getHint().toString();
                    }
                    String clientchannel = etClientChannel.getText().toString();
                    if (TextUtils.isEmpty(clientchannel)) {
                        clientchannel = etClientChannel.getHint().toString();
                    }
                    ClientEngine.getInstance().VERSION = clientVersion;
                    HPLog.e("welcome", "ClientEngine.VERSION" + ClientEngine.getInstance().VERSION);
                    NoCardPayConfig.CLIENTCHANNEL = clientchannel;

                    if (NoCardPayConfig.isUseHTTPS) {
                        ClientEngine.getInstance().init(WelcomeActivity.this.getApplicationContext(), NoCardPayConfig.ENV.HPV, "https://" + domain.trim() + "/" + NoCardPayConfig.URL_PATH, channel);
                    } else {
                        ClientEngine.getInstance().init(WelcomeActivity.this.getApplicationContext(), NoCardPayConfig.ENV.HPV, "http://" + domain.trim() + ":" + port.trim() + "/" + NoCardPayConfig.URL_PATH, channel);
                    }
                    paramers.put(BaseProtocolKey.VERSION, ClientEngine.getInstance().VERSION);
                    mVersionPresenter.checkVersion(paramers, false);

                    ClientEngine.getInstance().NO_CARD_PAYMENT_URL_TEST = no_card_pay_url_et.getText().toString();
                    ClientEngine.getInstance().QR_CODE_PAY_URL_TEST = qr_code_url_et.getText().toString();
                    ClientEngine.getInstance().LOTTERY_URL_TEST = lottery_url_et.getText().toString();

                }
            });
            builder.setCancelable(false);
            dialog = builder.create();
            dialog.show();
        } else {
            if (!NoCardPayConfig.ENV.CANSET) {
                if (NoCardPayConfig.isUseHTTPS) {
                    ClientEngine.getInstance().init(this, NoCardPayConfig.ENV.HPV, "https://" + NoCardPayConfig.ENV.SERVER.trim() + "/" + NoCardPayConfig.URL_PATH, NoCardPayConfig.ENV.CHAN);
                } else {
                    ClientEngine.getInstance().init(this, NoCardPayConfig.ENV.HPV, "http://" + NoCardPayConfig.ENV.SERVER.trim() + ":" + NoCardPayConfig.ENV.PORT + "/" + NoCardPayConfig.URL_PATH, NoCardPayConfig.ENV.CHAN);
                }
            }
            paramers.put(BaseProtocolKey.VERSION, ClientEngine.getInstance().VERSION);
            mVersionPresenter.checkVersion(paramers, false);
        }
    }

}
